package interval

import (
	"time"
)

var (
	MinTimerDuration time.Duration
)

type IntervalEngineer interface {
	OpenInterval(id interface{}, interval time.Duration, fn func()) (err error)
	CloseInterval(id interface{}) error
}

func SetDefaultIntervalEngineer(e IntervalEngineer) {
	if e == nil {
		panic("defaultIntervalEngine cannot be nil")
	}
	defaultIntervalEngineer = e
}

var (
	defaultIntervalEngineer IntervalEngineer
)

func OpenInterval(id interface{}, interval time.Duration, fn func()) (err error) {
	return defaultIntervalEngineer.OpenInterval(id, interval, fn)
}

func CloseInterval(id interface{}) error {
	return defaultIntervalEngineer.CloseInterval(id)
}

func testMinInterval() time.Duration {
	tm := time.NewTimer(1)
	defer tm.Stop()
	t0 := time.Now()
	select {
	case <-tm.C:
	}
	return time.Since(t0)
}

func init() {
	sum := time.Duration(0)
	for i := 0; i < 10; i++ {
		sum += testMinInterval()
	}
	MinTimerDuration = sum / 10
	SetDefaultIntervalEngineer(NewIntervalListEngine())
}
